package com.maodou.android.ui.page.account

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowLeft
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.maodou.android.R
import com.maodou.android.data.model.AccountCategoryVo
import com.maodou.android.viewmodel.account.CategoryViewModel
import com.maodou.core.navigation.DialogStyle
import com.maodou.core.navigation.GlobalUiBus
import com.maodou.core.navigation.LocalDialogHandle
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.ActionBar
import com.maodou.core.ui.components.AppText
import com.maodou.core.ui.components.EmptyCenterLayout
import com.maodou.core.ui.components.HSpacer
import com.maodou.core.ui.components.LoadMoreState
import com.maodou.core.ui.components.RefreshableLazyColumn
import com.maodou.core.ui.components.TitleAlignment
import com.maodou.core.ui.components.debouncedClickable
import com.maodou.core.ui.components.textfield.FormField
import com.maodou.core.utils.Logger
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @Author Xing
 * @CreateTime 2025年09月19日
 * @Description 账号自定义分类列表
 */
@Composable
fun CategoryListScreen(
    viewModel: CategoryViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val lazyState = rememberLazyListState()
    var categoryName by remember { mutableStateOf("") }

    val navigationBarHeight = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()

    Column {
        ActionBar(
            title = "账号分类管理",
            modifier = Modifier.fillMaxWidth(),
            navigationIcon = Icons.AutoMirrored.Outlined.KeyboardArrowLeft,
            onNavigationClick = {
                Navigator3.pop()
            },
            backgroundColor = Color.Transparent,
            contentColor = MaterialTheme.colorScheme.onSurface,
            titleAlignment = TitleAlignment.Center,
        )

        Box(modifier = Modifier.fillMaxWidth().weight(1f)) {
            RefreshableLazyColumn(
                items = uiState.categoryList,
                listState = lazyState,
                key = { item -> "${item.name}"},
                refreshing = uiState.isRefresh,
                onRefresh = {
                    viewModel.request()
                },
                loadMoreState = LoadMoreState.Idle,
                onLoadMore = {

                },
                contentPadding = PaddingValues(12.dp),
                emptyContent = { EmptyCenterLayout() }
            ) { item ->
                AccountCategoryItem(
                    item,
                    edit = {
                        categoryName = "${item.name}"
                        GlobalUiBus.showPopup(
                            style = DialogStyle.Bottom,
                            dismissOnClickOutside = true,
                            dismissOnBackPress = false,
                            content = {
                                val handle = LocalDialogHandle.current
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    FormField(
                                        value = categoryName,
                                        onValueChange = { categoryName = it },
                                        label = "",
                                        modifier = Modifier.weight(1f),
                                        placeholder = "请输入分类",
                                        maxLength = 30,
                                        borderless = true
                                    )

                                    Box(
                                        modifier = Modifier
                                            .height(40.dp).width(64.dp)
                                            .padding(end = 12.dp)
                                            .background(color = MaterialTheme.colorScheme.primary,RoundedCornerShape(6.dp))
                                            .debouncedClickable(enabled = !uiState.isLoading) {
                                                viewModel.editCategory(item.id,categoryName) {
                                                    handle?.close()
                                                }
                                            },
                                        contentAlignment = Alignment.Center
                                    ) {
                                        if (uiState.isLoading) {
                                            CircularProgressIndicator(
                                                modifier = Modifier.size(16.dp),
                                                strokeWidth = 2.dp,
                                                color = Color.White
                                            )
                                        } else Text(text = "确认", textAlign = TextAlign.Center, color = Color.White, fontSize = 12.sp)
                                    }
                                }
                            }
                        )
                    },
                    delete = {
                        viewModel.deleteCategory(item.id)
                    }
                )
            }

            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .align(Alignment.BottomCenter)
                    .padding(start = 20.dp, end = 20.dp, bottom =  20.dp + navigationBarHeight),
            ) {
                Button(
                    onClick = {
                        GlobalUiBus.showPopup(
                            style = DialogStyle.Bottom,
                            dismissOnClickOutside = true,
                            dismissOnBackPress = false,
                            content = {
                                val handle = LocalDialogHandle.current
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    FormField(
                                        value = categoryName,
                                        onValueChange = { categoryName = it },
                                        label = "",
                                        modifier = Modifier.weight(1f),
                                        placeholder = "请输入分类",
                                        maxLength = 30,
                                        borderless = true
                                    )

                                    Box(
                                        modifier = Modifier
                                            .height(40.dp).width(64.dp)
                                            .padding(end = 12.dp)
                                            .background(color = MaterialTheme.colorScheme.primary,RoundedCornerShape(6.dp))
                                            .debouncedClickable(enabled = !uiState.isLoading) {
                                                viewModel.addCategory(categoryName) {
                                                    handle?.close()
                                                }
                                            },
                                        contentAlignment = Alignment.Center
                                    ) {
                                        Text(text = "确认", textAlign = TextAlign.Center, color = Color.White, fontSize = 12.sp)
                                    }
                                }
                            }
                        )
                    },
                    enabled = true,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(48.dp),
                    shape = RoundedCornerShape(12.dp)
                ) {
                    Text(text = "添加分类", textAlign = TextAlign.Center)
                }
            }

        }

    }
}

@Composable
fun AccountCategoryItem(item:AccountCategoryVo,edit:() -> Unit,delete:() -> Unit){
    Surface(
        modifier = Modifier
            .fillMaxSize()
            .padding(vertical = 5.dp, horizontal = 12.dp),
        shape = RoundedCornerShape(12.dp),
        color = Color.White,
        shadowElevation = 2.dp
    ) {
        Row(
            modifier = Modifier.height(56.dp).padding(start = 12.dp, end = 6.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            AppText(
                text = "${item.name}",
                style = TextStyle(
                    fontSize = 16.sp,
                    fontWeight = FontWeight.SemiBold
                ),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                modifier = Modifier.weight(1f)
            )

            Box(
                modifier = Modifier.height(50.dp).width(32.dp).debouncedClickable { edit() },
                contentAlignment = Alignment.Center
            ) {
                Image(
                    painter = painterResource(R.mipmap.ic_category_edit),
                    contentDescription = null,
                    modifier = Modifier.size(16.dp)
                )
            }
            Box(
                modifier = Modifier.height(50.dp).width(32.dp).debouncedClickable { delete() },
                contentAlignment = Alignment.Center
            ) {
                Image(
                    painter = painterResource(R.mipmap.ic_category_delete),
                    contentDescription = null,
                    modifier = Modifier.size(16.dp)
                )
            }
        }
    }
}

@Preview(backgroundColor = 0xffffffff)
@Composable
fun CategoryListScreenPreview(){
    CategoryListScreen()
}